import React, { Component } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { push } from 'connected-react-router'
import { global as globalDuck } from 'ducks'
import { Switch, Redirect } from 'react-router'
import { PrivateRoute } from 'components/route'
import Members from './members'
import Teams from './teams'
import Nav from './userNav'

class Datasets extends Component {
  state = {}

  static propTypes = {
    actionSetActiveNavItem: PropTypes.func.isRequired,
  }

  setActiveItem = item => this.setState({ activeItem: item })

  componentDidMount = () => {
    const { setParentActiveItem } = this.props
    setParentActiveItem('user')
  }

  render() {
    const { match, location, org } = this.props
    const orgName = org.owner_object.name
    const { activeItem } = this.state
    return (
      <React.Fragment>
        <Nav orgName={orgName} activeItem={activeItem} />
        <Switch location={location}>
          <PrivateRoute
            path={`${match.url}/members`}
            render={props => (
              <Members {...props} setParentActiveItem={this.setActiveItem} org={org} />
            )}
            exact={false}
          />
          <PrivateRoute
            path={`${match.url}/teams`}
            render={props => (
              <Teams {...props} setParentActiveItem={this.setActiveItem} org={org} />
            )}
            exact={false}
          />
          <Redirect from={`${match.url}`} to={`${match.url}/members`} />
        </Switch>
      </React.Fragment>
    )
  }
}

const mapStateToProps = state => ({
  user: globalDuck.selectors.user(state),
})

const mapDispatchToProps = {
  actionSetActiveNavItem: globalDuck.creators.actionSetActiveNavItem,
  link: path => push(path),
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(Datasets)
